package model;

import jade.core.AID;

import java.io.Serializable;
import java.util.Vector;

public class Plan implements Serializable {
	private static final long serialVersionUID = 1L;

	Vector<Step> steps;

	public Plan() {
		steps = new Vector<Step>();
	}

	public Plan(AID sourceID, AID destinationID, Position source,
			Position destination, Product product) {
		Step s = new Step(sourceID, destinationID, source, destination, product);
		steps = new Vector<Step>();
		steps.add(s);
	}

	public float getTotalDistance(Position p) {
		float accumulatedDistance = 0f;
		for (int i = 0; i != steps.size(); i++) {
			if (i + 1 >= steps.size()) {
				accumulatedDistance += steps.get(i).getTotalDistance(p);
			} else {
				accumulatedDistance += steps.get(i).getTotalDistance(
						steps.get(i + 1).getSource());
			}
		}
		return accumulatedDistance;
	}

	public float getTotalDistancePlusRecharge(Step evalStep, Position currentPlace, Position recharge)
	{
		return getTotalDistance(evalStep,currentPlace) + evalStep.getDestination().findDistance(recharge);
	}
	
	public float getTotalDistance(Step evalStep, Position currentPlace) {
		float accumulatedDistance = 0f;
		Position lastPlace = currentPlace;
		for (int i = 0; i != steps.size(); i++) {
			accumulatedDistance += steps.get(i).getTotalDistance(lastPlace);
			lastPlace = steps.get(i).getDestination();
		}
		accumulatedDistance += evalStep.getTotalDistance(lastPlace);
		return accumulatedDistance;
	}

	public Product getProduct() {
		return steps.firstElement().getProduct();
	}

	public Position getSource() {
		if (hasSteps()) {
			return steps.firstElement().getSource();
		} else {
			return null;
		}
	}

	public Position getDestination() {
		return steps.firstElement().getDestination();
	}

	public void pickupPerformed() {
		steps.firstElement().pickupPerformed();
	}

	public AID getSourceID() {
		return steps.firstElement().getSourceID();
	}

	public AID getDestinationID() {
		return steps.firstElement().getDestinationID();
	}

	public boolean hasSteps() {
		return !steps.isEmpty();
	}

	public void addStep(Step s) {
		steps.add(s);

	}

	public void dropStep() {
		//remove first
		steps.remove(0);
		
	}
	@Override
	public String toString() {
		String result = "";
		for(int i = 0; i != steps.size(); i++)
		{
			 result += steps.get(i).toString() + ",";
		}
		return result;
	}

	public Step getCurrentStep() {
		return steps.get(0);
	}

	public Step getLastStep() {
		return steps.lastElement();
	}
}
